﻿﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.IO;
using HomeCareLibrary.Core.DataContracts;
using HomeCareLibrary.AppService;
using System.Web.Script.Serialization;
using HomeCareLibrary.Core.JsonObjects;

namespace HomeWizardServices
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class Service1 : IService1
    {
        public string TestMethod(string name)
        {
            return string.Format("Welcome {0}", name);
        }
        
        public Stream getApp_Check_Promocode(CheckPromocodeRequest promocodeRequest)
        {
            var service = new SponsorAppService();
            var returnData = service.CheckPromoCode(promocodeRequest);
            var dictionaryData = new Dictionary<string, string>();
            returnData.ForEach(promoCode =>
            {
                dictionaryData.Add("promoCodeCheck", promoCode.PromocodeCheck);
            });
            return WriteJson(dictionaryData);
        }

        public Stream getApp_Initial_Setup(SponsorData sponsorData)
        {
            var service = new SponsorAppService();
            var returnData = service.InitialSetup(sponsorData);
            var dictionaryData = new Dictionary<string, string>();
            returnData.ForEach(result =>
            {
                dictionaryData.Add("initialSetup", result.InitialSetup);
                dictionaryData.Add("userId", result.user_id.HasValue ? result.user_id.Value.ToString() : null);
                dictionaryData.Add("userName", result.user_name);
                dictionaryData.Add("password", result.password);
                dictionaryData.Add("promoCode", result.sponsor);
                dictionaryData.Add("welcomeImage", result.welcome_image);
                dictionaryData.Add("welcomeImageChangeTime", result.welcome_image_chg_time);
                dictionaryData.Add("iNameLine", result.iname_line);
                if(result.iadmin_link != string.Empty)
                {
                    dictionaryData.Add("iAdminLink", result.iadmin_link);
                }
                else
                {
                    dictionaryData.Add("iAdminLink", result.icompany_name ?? "Compliments Of");
                }
                dictionaryData.Add("iCompanyName", result.icompany_name);
                dictionaryData.Add("iEmailAddress", result.iemail_address);
                dictionaryData.Add("iPhoneNumber", result.iphone_number);
                dictionaryData.Add("iTagLine", result.itagline);
                dictionaryData.Add("iWebSite", result.iwebsite);
                dictionaryData.Add("sponChangeTime", result.spon_change_time);
                dictionaryData.Add("iLogoPic", result.ilogo_pic);
                dictionaryData.Add("iLogoPicChangeTime", result.ilogo_pic_chg_time);
                dictionaryData.Add("sponsorStatus", result.sponsorStatus);
            });
            return WriteJson(dictionaryData);
        }

        public Stream getApp_Initial_Login(SponsorData sponsorData)
        {
            return DataAccess.getApp_Initial_Login(sponsorData);
        }

        public Stream getApp_Reopen(AppReopenRequest appReopenRequest)
        {            
            return DataAccess.getApp_Reopen(appReopenRequest);
        }
        
        public Stream getApp_Forgot_Password(ForgotPasswordRequest forgotPasswordRequest)
        {
            return DataAccess.getApp_Forgot_Password(forgotPasswordRequest);
        }
        
        public Stream getRoutineTaskList(GetRoutineTasksRequest postdata)
        {
            var service = new TasksAppService();
            var returnData = service.GetRoutineTasks(new GetRoutineTasksRequest
            {
                DwellPriorityKLLoc = postdata.DwellPriorityKLLoc,
                 FeatureString =postdata.FeatureString,
             Goal = postdata.Goal,
             Turn_Offs = postdata.Turn_Offs,
             StartMonth = postdata.StartMonth,
             StartYear = postdata.StartYear,
             RequestedMonth = postdata.RequestedMonth,
             RequestedYear =postdata.RequestedYear,
             UserId = postdata.UserId,
             HomeNumber = postdata.HomeNumber
            });
            var dictionaryData = new Dictionary<string, string>();
            returnData.ForEach(TasksAppService =>
            {
                dictionaryData.Add("task_code", TasksAppService.task_code);
                dictionaryData.Add("display_icon_code", TasksAppService.display_icon_code);
                dictionaryData.Add("rc_task_title", TasksAppService.rc_task_title);
                dictionaryData.Add("rc_task_content", TasksAppService.rc_task_content);
                dictionaryData.Add("rc_rec_timing", TasksAppService.rc_rec_timing);
                dictionaryData.Add("rc_priority", TasksAppService.rc_priority.ToString());
                dictionaryData.Add("rc_type", TasksAppService.rc_type.ToString());
                dictionaryData.Add("rc_benefit_content", TasksAppService.rc_benefit_content);
                dictionaryData.Add("rc_energy_savings_score", TasksAppService.rc_energy_savings_score.ToString());
                dictionaryData.Add("rc_energy_savings_content", TasksAppService.rc_energy_savings_content);
                dictionaryData.Add("rc_cost_score", TasksAppService.rc_cost_score.ToString());
                dictionaryData.Add("rc_cost_content", TasksAppService.rc_cost_content.ToString());
                dictionaryData.Add("rc_more_info_link", TasksAppService.rc_more_info_link.ToString());
                dictionaryData.Add("rc_knowledge_level", TasksAppService.rc_knowledge_level.ToString());
                dictionaryData.Add("rc_cycle_timing", TasksAppService.rc_cycle_timing.ToString());
                dictionaryData.Add("rc_timing_months", TasksAppService.rc_timing_months.ToString());
                dictionaryData.Add("TGMS", TasksAppService.TGMS);
                dictionaryData.Add("benefits_str", TasksAppService.benefits_str.ToString());
                dictionaryData.Add("IsChecked", TasksAppService.IsChecked.ToString());
            });
            return WriteJson(dictionaryData);
        }

        public Stream getApp_MoReminder_Refresh(MonthlyReminderRefreshRequest request)
        {
            var service = new AppRefreshAppService();
            var returnData = service.CheckMonthlyReminderRefresh(request);

            var dictionaryData = new Dictionary<string, string>();
            dictionaryData.Add("appUpdate", returnData.AppUpdate);

            if (returnData.AppUpdate.ToLower() == "monthlyreminderchanged")
            {
                dictionaryData.Add("appMoAlertWeek", returnData.MOAlertWeekly.HasValue ? returnData.MOAlertWeekly.Value.ToString() : string.Empty);
                dictionaryData.Add("appMoAlertDay", returnData.MOAlertDay.HasValue ? returnData.MOAlertDay.Value.ToString() : string.Empty);
                dictionaryData.Add("appMoAlertHour", returnData.MOAlertHour.HasValue ? returnData.MOAlertHour.Value.ToString() : string.Empty);
                dictionaryData.Add("appMoAlertBadge", returnData.MOAlertBadge.HasValue ? returnData.MOAlertBadge.Value.ToString() : string.Empty);
                dictionaryData.Add("appMoAlertPopup", returnData.MOAlertPopup.HasValue ? returnData.MOAlertPopup.Value.ToString() : string.Empty);
            }

            return WriteJson(dictionaryData);
        }

        public Stream getApp_PromoCode_Refresh(PromoCodeRefreshRequest request)
        {
            var service = new AppRefreshAppService();
            var returnData = service.CheckPromocodeRefresh(request);

            var dictionaryData = new Dictionary<string, string>();
            dictionaryData.Add("appUpdate", returnData.AppUpdate);
            dictionaryData.Add("promoCode", returnData.SavedPromoCode ?? string.Empty);
            dictionaryData.Add("iNameLine", returnData.iNameLine ?? string.Empty);
            if (returnData.iAdminLink != string.Empty)
            {
                dictionaryData.Add("iAdminLink", returnData.iAdminLink);
            }
            else
            {
                dictionaryData.Add("iAdminLink", returnData.iCompanyName ?? "Compliments Of");
            }
            dictionaryData.Add("iCompanyName", returnData.iCompanyName ?? string.Empty);
            dictionaryData.Add("iEmailAddress", returnData.iEmailAddress ?? string.Empty);
            dictionaryData.Add("iPhoneNumber", returnData.iPhoneNumber ?? string.Empty);
            dictionaryData.Add("iTagLine", returnData.iTagLine ?? string.Empty);

            //dictionaryData.Add("iWebSite", returnData.iwebsite ?? string.Empty);

            dictionaryData.Add("iWebSite", returnData.iWebSite ?? string.Empty);

            dictionaryData.Add("sponChangeTime", returnData.sponChangeTime ?? string.Empty);
            dictionaryData.Add("iLogoPic", returnData.iLogoPic ?? string.Empty);
            dictionaryData.Add("iLogoPicChangeTime", returnData.iLogoPicChangeTime ?? string.Empty);
            dictionaryData.Add("sponsorStatus", returnData.sponsorStatus ?? string.Empty);

            return WriteJson(dictionaryData);
        }

        public Stream getApp_Update_UserNamePassword(UpdateUserNamePasswordRequest request)
        {
            var service = new UserAppService();
            var returnData = service.UpdateUserNamePassword(request);
            
            var dictionaryData = new Dictionary<string, object>();

            if (returnData != null && returnData.Count > 0)
            {
                dictionaryData.Add("updateUserName", returnData[0].user_name);
                dictionaryData.Add("updatePassword", returnData[0].password);
            }
            return WriteJson(dictionaryData);
        }

        #region Personalization Web Services
        public Stream getApp_PES_GetFeaturesByUserIdHomeNumber(GetKLByUserIdHomeNumberRequest request)
        {
            //string subject = "getApp_PES_GetFeaturesByUserIdHomeNumber";
            //string body = string.Empty;

            //body += request.UserId.ToString() + ",";
            //body += request.HomeNumber.ToString();

            //HomeWizardEmail.SendEmail(subject, body);

            var service = new PersonalisationAppService();
            var returnData = service.GetFeaturesByUserIdHomeNumber(request);
            var dictionaryData = new Dictionary<string, object>();
            returnData.ForEach(feature =>
            {                
                dictionaryData.Add("userId", feature.user_id);
                dictionaryData.Add("homeNumber", feature.home_number);
                dictionaryData.Add("dwellingType", feature.dwelling_type);
                dictionaryData.Add("featurestring", feature.featurestring != null ? feature.featurestring : string.Empty);
            });
            return WriteJson(dictionaryData);
        }

        public Stream getApp_PES_GetCountryStates()
        {
            var service = new PersonalisationAppService();
            var returnData = service.GetCountryStates();
            List<Country> countries = new List<Country>();
            Country country = null;
            StateProvince stateProvince = null;
            string countryCode = string.Empty;

            if (returnData != null && returnData.Count > 0)
            {             
                returnData.ForEach(countryState =>
                {
                    if (countryCode.ToLower() != countryState.country.ToLower())
                    {
                        country = new Country();
                        country.countryCode = countryState.country != null ? countryState.country : string.Empty;
                        country.countryName = countryState.country_name != null ? countryState.country_name : string.Empty;
                        countryCode = country.countryCode;
                        countries.Add(country);
                    }
                    stateProvince = new StateProvince();
                    stateProvince.stateProvinceCode = countryState.state_province_code != null ? countryState.state_province_code : string.Empty; ;
                    stateProvince.stateProvinceName = countryState.state_or_province_name != null ? countryState.state_or_province_name : string.Empty;
                    country.stateProvinces.Add(stateProvince);
                });
            }
            return WriteJson(countries);
        }

        public Stream getApp_PES_GetDwellingTypes()
        {
            var service = new PersonalisationAppService();
            var returnData = service.GetDwellingTypes();
            List<DwellingType> dwellingTypes = new List<DwellingType>();
            DwellingType dwellingType = null;

            returnData.ForEach(dwType =>
            {
                dwellingType = new DwellingType();
                dwellingType.dwellingCode = dwType.dwelling_code;
                dwellingType.dwellingType = dwType.dwelling_type != null ? dwType.dwelling_type : string.Empty;
                dwellingTypes.Add(dwellingType);
            });
            return WriteJson(dwellingTypes);
        }

        public Stream getApp_PES_GetFeatureCategories()
        {
            var service = new PersonalisationAppService();
            var returnData = service.FetchFeatureCategories();
            List<FeatureCategory> featureCategories = new List<FeatureCategory>();
            FeatureCategory featureCategory = null;

            returnData.ForEach(category =>
            {
                featureCategory = new FeatureCategory();
                featureCategory.id = category.ID;
                featureCategory.category = category.HomeCareLibrary_Category != null ? category.HomeCareLibrary_Category : string.Empty;
                featureCategories.Add(featureCategory);
            });
            return WriteJson(featureCategories);
        }

        public Stream getApp_PES_GetLocationByUserIdHomeNumber(GetKLByUserIdHomeNumberRequest request)
        {

            //string subject = "getApp_PES_GetLocationByUserIdHomeNumber";
            //string body = string.Empty;

            //body += request.UserId.ToString() + ",";
            //body += request.HomeNumber.ToString();

            //HomeWizardEmail.SendEmail(subject, body);

            var service = new PersonalisationAppService();
            var returnData = service.GetLocationByUserIdHomeNumber(request);
            var dictionaryData = new Dictionary<string, object>();
            returnData.ForEach(location =>
            {
                dictionaryData.Add("userId", location.user_id);
                dictionaryData.Add("homeNumber", location.home_number);
                dictionaryData.Add("psCountry", location.ps_country != null ? location.ps_country : string.Empty);
                dictionaryData.Add("psStateProvince", location.ps_state_province != null ? location.ps_state_province : string.Empty);               
            });
            return WriteJson(dictionaryData);
        }

        public Stream getApp_PES_GetPriorityLevelByUserIdHomeNumber(GetKLByUserIdHomeNumberRequest request)
        {
            //string subject = "getApp_PES_GetPriorityLevelByUserIdHomeNumber";
            //string body = string.Empty;

            //body += request.UserId.ToString() + ",";
            //body += request.HomeNumber.ToString();

            //HomeWizardEmail.SendEmail(subject, body);

            var service = new PersonalisationAppService();
            var returnData = service.GetPriorityLevelByUserIdHomeNumber(request);
            var dictionaryData = new Dictionary<string, object>();
            returnData.ForEach(pl =>
            {
                dictionaryData.Add("userId", pl.user_id);
                dictionaryData.Add("homeNumber", pl.home_number);
                dictionaryData.Add("psPriority", pl.ps_priority != null ? pl.ps_priority.ToString() : string.Empty);
            });
            return WriteJson(dictionaryData);
        }

        public Stream getApp_PES_GetGoalsByUserIdHomeNumber(GetKLByUserIdHomeNumberRequest request)
        {
            //string subject = "getApp_PES_GetGoalsByUserIdHomeNumber";
            //string body = string.Empty;

            //body += request.UserId.ToString() + ",";
            //body += request.HomeNumber.ToString();

            //HomeWizardEmail.SendEmail(subject, body);

            var service = new PersonalisationAppService();
            var returnData = service.GetGoalsByUserIdHomeNumber(request);
            var dictionaryData = new Dictionary<string, object>();
            returnData.ForEach(goal =>
            {
                dictionaryData.Add("userId", goal.user_id);
                dictionaryData.Add("homeNumber", goal.home_number);
                dictionaryData.Add("psGoalString", goal.ps_goal_string != null ? goal.ps_goal_string : string.Empty);
            });
            return WriteJson(dictionaryData);
        }

        public Stream getApp_PES_GetMonthlyAlertSettingsByUserIdHomeNumber(GetKLByUserIdHomeNumberRequest request)
        {
            //string subject = "getApp_PES_GetMonthlyAlertSettingsByUserIdHomeNumber";
            //string body = string.Empty;

            //body += request.UserId.ToString() + ",";
            //body += request.HomeNumber.ToString();

            //HomeWizardEmail.SendEmail(subject, body);

            var service = new PersonalisationAppService();
            var returnData = service.GetMonthlyAlertSettingsByUserIdHomeNumber(request);
            var dictionaryData = new Dictionary<string, object>();
            returnData.ForEach(alertSetting =>
            {
                dictionaryData.Add("userId", alertSetting.user_id);
                dictionaryData.Add("homeNumber", alertSetting.home_number);
                dictionaryData.Add("webMoAlertEmail", alertSetting.web_mo_alert_email);
                dictionaryData.Add("appMoAlertWeek", alertSetting.app_mo_alert_week != null ? alertSetting.app_mo_alert_week.Value : 0);
                dictionaryData.Add("appMoAlertDay", alertSetting.app_mo_alert_day != null ? alertSetting.app_mo_alert_day.Value : 0);
                dictionaryData.Add("appMoAlertHour", alertSetting.app_mo_alert_hour != null ? alertSetting.app_mo_alert_hour.Value : 0);
                dictionaryData.Add("appMoAlertBadge", alertSetting.app_mo_alert_badge != null ? alertSetting.app_mo_alert_badge.Value : 0);
                dictionaryData.Add("appMoAlertPopup", alertSetting.app_mo_alert_popup != null ? alertSetting.app_mo_alert_popup.Value : 0);
            });
            return WriteJson(dictionaryData);
        }
                
        public Stream getApp_PES_GetUserHomes(GetUserHomeRequest request)
        {
            //string subject = "getApp_PES_GetUserHomes";
            //string body = string.Empty;

            //body += request.UserId.ToString();           

            //HomeWizardEmail.SendEmail(subject, body);

            var service = new PersonalisationAppService();
            var returnData = service.GetUserHomes(request);
            UserHomes userHomes = null;
            if (returnData != null && returnData.Count > 0)
            {
                userHomes = new UserHomes(returnData);
            }

            return WriteJson(userHomes);

        }

        public Stream getApp_PES_GetFeaturesByDwellingCode(GetFeaturesByDwellingTypeRequest request)
        {
            //string subject = "getApp_PES_GetFeaturesByDwellingCode";
            //string body = string.Empty;

            //body += request.DwellingCode.ToString();

            //HomeWizardEmail.SendEmail(subject, body);

            var service = new PersonalisationAppService();
            var returnData = service.GetFeaturesByDwellingCode(request);
            List<FeatureCategory> featureCategories = new List<FeatureCategory>();
            FeatureCategory featureCategory = null;
            Feature feature = null;
            int categoryId = 0;

            if (returnData != null && returnData.Count > 0)
            {
                returnData.ForEach(fet =>
                {
                    if (categoryId != fet.categoryID)
                    {
                        featureCategory = new FeatureCategory();
                        featureCategory.id = fet.categoryID.HasValue ? fet.categoryID.Value : 0;
                        featureCategory.category = fet.HomeCareLibrary_Category;
                        featureCategories.Add(featureCategory);
                        categoryId = fet.categoryID.HasValue ? fet.categoryID.Value : 0;
                    }
                    feature = new Feature();
                    feature.featureCode = fet.feature_code;
                    feature.featureName = fet.feature_name;
                    featureCategory.features.Add(feature);
                });
            }
            return WriteJson(featureCategories);
        }

        /// <summary>
        /// Gets the app's default features by dwelling code.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public Stream getApp_PES_GetDefaultFeaturesByDwellingCode(GetFeaturesByDwellingTypeRequest request)
        {
            //string subject = "getApp_PES_GetDefaultFeaturesByDwellingCode";
            //string body = string.Empty;

            //body += request.DwellingCode.ToString();

            //HomeWizardEmail.SendEmail(subject, body);

            var service = new PersonalisationAppService();
            var returnData = service.GetDefaultFeaturesByDwellingCode(request);
            List<FeatureCategory> featureCategories = new List<FeatureCategory>();
            FeatureCategory featureCategory = null;
            Feature feature = null;
            int categoryId = 0;

            if (returnData != null && returnData.Count > 0)
            {
                returnData.ForEach(fet =>
                {
                    if (categoryId != fet.categoryID)
                    {
                        featureCategory = new FeatureCategory();
                        featureCategory.id = fet.categoryID.HasValue ? fet.categoryID.Value : 0;
                        featureCategories.Add(featureCategory);
                        categoryId = fet.categoryID.HasValue ? fet.categoryID.Value : 0;
                    }
                    feature = new Feature();
                    feature.featureCode = fet.feature_code;
                    featureCategory.features.Add(feature);
                });
            }
            return WriteJson(featureCategories);
        }

        /// <summary>
        /// Gets the feature by identifier for APP.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public Stream getApp_PES_GetFeatureById(GetFeaturesByIdRequest request)
        {
            //string subject = "getApp_PES_GetFeatureById";
            //string body = string.Empty;

            //body += request.FeatureCode.ToString();

            //HomeWizardEmail.SendEmail(subject, body);

            var service = new PersonalisationAppService();
            var returnData = service.GetFeatureById(request.FeatureCode);
            var dictionaryData = new Dictionary<string, object>();
            if (returnData != null)
            {
                dictionaryData.Add("featureCode", returnData.feature_code != null ? returnData.feature_code.ToString() : string.Empty);
                dictionaryData.Add("categoryId", returnData.categoryID != null ? returnData.categoryID.Value : 0);
                dictionaryData.Add("featureName", returnData.feature_name != null ? returnData.feature_name : string.Empty);
                dictionaryData.Add("featureTaskImage", returnData.feature_task_image != null ? returnData.feature_task_image : string.Empty);
                dictionaryData.Add("featureDescription", returnData.feature_description != null ? returnData.feature_description : string.Empty);
            }
            return WriteJson(dictionaryData);
        }

        public Stream getApp_PES_GetKnowledgeLevelByUserIdHomeNumber(GetKLByUserIdHomeNumberRequest request)
        {
            //string subject = "getApp_PES_GetKnowledgeLevelByUserIdHomeNumber";
            //string body = string.Empty;

            //body += request.UserId.ToString() + ",";
            //body += request.HomeNumber.ToString();

            //HomeWizardEmail.SendEmail(subject, body);

            var service = new PersonalisationAppService();
            var returnData = service.GetKnowledgeLevelByUserIdHomeNumber(request);
            var dictionaryData = new Dictionary<string, object>();
            returnData.ForEach(kl =>
            {
                dictionaryData.Add("userId", kl.user_id);
                dictionaryData.Add("homeNumber", kl.home_number);
                dictionaryData.Add("psKnowledgeLevel", kl.ps_knowledge_level != null ? kl.ps_knowledge_level.ToString() :string.Empty);
            });
            return WriteJson(dictionaryData);
        }

        public Stream getApp_PES_UpdatePersonalization(PersonalizationData personalisationData)
        {
            //string subject = "getApp_PES_UpdatePersonalization";
            //string body = string.Empty;

            //body += personalisationData.UserId.ToString() + ",";
            //body += personalisationData.DwellingType.ToString() + ",";
            //body += personalisationData.HomeNumber.ToString() + ",";
            //body += personalisationData.HomeName.ToString() + ",";
            //body += personalisationData.FeatureString.ToString() + ",";
            //body += personalisationData.Country.ToString() + ",";
            //body += personalisationData.StateProvince.ToString() + ",";
            //body += personalisationData.Goal.ToString() + ",";
            //body += personalisationData.KnowledgeLevel.ToString() + ",";
            //body += personalisationData.Priority.ToString();
            
            //HomeWizardEmail.SendEmail(subject, body);

            var service = new PersonalisationAppService();            
            var returnData = service.UpdatePersonalization(personalisationData);
            var dictionaryData = new Dictionary<string, string>();
            dictionaryData.Add("result", returnData);
            return WriteJson(dictionaryData);
        }

        public Stream getApp_PES_AddHome(HomeData request)
        {
            //string subject = "getApp_PES_AddHome";
            //string body = string.Empty;

            //body += request.UserId.ToString() + ",";
            //body += request.HomeNumber.ToString() + ",";
            //body += request.HomeName.ToString() + ",";
            //body += request.DwellingType.ToString() + ",";
            //body += request.FeatureString.ToString() + ",";
            //body += request.Priority.ToString() + ",";
            //body += request.KnowledgeLevel.ToString() + ",";
            //body += request.Country.ToString() + ",";
            //body += request.StateProvince.ToString() + ",";
            //body += request.Goal.ToString() + ",";
            //body += request.TurnOffs.ToString() + ",";
            //body += request.StartMonth.ToString() + ",";
            //body += request.StartYear.ToString() + ",";

            //HomeWizardEmail.SendEmail(subject, body);

            var service = new PersonalisationAppService();
            var returnData = service.AddHome(request.UserId);
            var dictionaryData = new Dictionary<string, object>();
            if (returnData != null && returnData.user_id > 0)
            {
                dictionaryData.Add("userId", returnData.user_id);
                dictionaryData.Add("homeNumber", returnData.home_number);
                dictionaryData.Add("homeName", returnData.home_name ?? string.Empty);
                dictionaryData.Add("dwellingType", returnData.dwelling_type);
                dictionaryData.Add("featureString", returnData.featurestring ?? string.Empty);
                dictionaryData.Add("psPriority", returnData.ps_priority.HasValue ? returnData.ps_priority.Value : 0 );
                dictionaryData.Add("psKnowledgeLevel", returnData.ps_knowledge_level.HasValue ? returnData.ps_knowledge_level.Value : 0);
                dictionaryData.Add("psCountry", returnData.ps_country ?? string.Empty);
                dictionaryData.Add("psStateProvince", returnData.ps_state_province ?? string.Empty);
                dictionaryData.Add("psGoalString", returnData.ps_goal_string ?? string.Empty);
                dictionaryData.Add("turnOffs", returnData.turn_offs ?? string.Empty);
                dictionaryData.Add("startMonth", returnData.start_month.HasValue ? returnData.start_month.Value : DateTime.Now.Month);
                dictionaryData.Add("startYear", returnData.start_year.HasValue ? returnData.start_year.Value : DateTime.Now.Year);
            }
            else
            {
                dictionaryData.Add("userId", string.Empty);
                dictionaryData.Add("homeNumber", string.Empty);
                dictionaryData.Add("homeName", string.Empty);
                dictionaryData.Add("dwellingType", string.Empty);
                dictionaryData.Add("featureString", string.Empty);
                dictionaryData.Add("psPriority", string.Empty);
                dictionaryData.Add("psKnowledgeLevel", string.Empty);
                dictionaryData.Add("psCountry", string.Empty);
                dictionaryData.Add("psStateProvince", string.Empty);
                dictionaryData.Add("psGoalString", string.Empty);
                dictionaryData.Add("turnOffs", string.Empty);
                dictionaryData.Add("startMonth", string.Empty);
                dictionaryData.Add("startYear", string.Empty);
            }
            return WriteJson(dictionaryData);  
        }
                
        public Stream getApp_PES_DeleteHome(HomeData homeData)
        {
            //string subject = "getApp_PES_DeleteHome";
            //string body = string.Empty;

            //body += homeData.UserId.ToString() + ",";
            //body += homeData.HomeNumber.ToString() + ",";
            //body += homeData.HomeName.ToString() + ",";
            //body += homeData.DwellingType.ToString() + ",";
            //body += homeData.FeatureString.ToString() + ",";
            //body += homeData.Priority.ToString() + ",";
            //body += homeData.KnowledgeLevel.ToString() + ",";
            //body += homeData.Country.ToString() + ",";
            //body += homeData.StateProvince.ToString() + ",";
            //body += homeData.Goal.ToString() + ",";
            //body += homeData.TurnOffs.ToString() + ",";
            //body += homeData.StartMonth.ToString() + ",";
            //body += homeData.StartYear.ToString() + ",";

            //HomeWizardEmail.SendEmail(subject, body);

            var service = new PersonalisationAppService();
            var returnData = service.DeleteHome(homeData);
            var dictionaryData = new Dictionary<string, string>();
            dictionaryData.Add("result", returnData);
            return WriteJson(dictionaryData);
        }

        public Stream getLocationGoalsKnowPriorityByUserIdHomeNum(GetKLByUserIdHomeNumberRequest request)
        {
            //string subject = "getLocationGoalsKnowPriorityByUserIdHomeNum";
            //string body = string.Empty;

            //body += request.UserId.ToString() + ",";
            //body += request.HomeNumber.ToString();

            //HomeWizardEmail.SendEmail(subject, body);

            var service = new PersonalisationAppService();
            var location = service.GetLocationByUserIdHomeNumber(request).FirstOrDefault();
            var priority = service.GetPriorityLevelByUserIdHomeNumber(request).FirstOrDefault();
            var knowledgeLevel = service.GetKnowledgeLevelByUserIdHomeNumber(request).FirstOrDefault();
            var goal = service.GetGoalsByUserIdHomeNumber(request).FirstOrDefault();

            var dictionaryData = new Dictionary<string, object>();
            dictionaryData.Add("userId", request.UserId);
            dictionaryData.Add("homeNumber", request.HomeNumber);
            dictionaryData.Add("psCountry", location != null ? location.ps_country : string.Empty);
            dictionaryData.Add("psStateProvince", location != null ? location.ps_state_province : string.Empty);
            dictionaryData.Add("psPriority", priority != null && priority.ps_priority.HasValue ? priority.ps_priority.Value : 0);
            dictionaryData.Add("psGoalString", goal !=null ? goal.ps_goal_string : string.Empty);
            dictionaryData.Add("psKnowledgeLevel", knowledgeLevel != null && knowledgeLevel.ps_knowledge_level.HasValue ? knowledgeLevel.ps_knowledge_level.Value : 0);

            return WriteJson(dictionaryData);
        }

        public Stream getApp_PES_GetFeaturesByUserIdHomeNumberDwellingType(GetFeaturesByUserIdHomeNumberDwellingTypeRequest request)
        {
            //string subject = "getApp_PES_GetFeaturesByUserIdHomeNumberDwellingType";
            //string body = string.Empty;

            //body += request.UserId.ToString() + ",";
            //body += request.HomeNumber.ToString() + ",";
            //body += request.DwellingType.ToString();

            //HomeWizardEmail.SendEmail(subject, body);

            var service = new PersonalisationAppService();
            var returnData = service.GetFeaturesByUserIdHomeNumberDwellingType(request.UserId, request.HomeNumber, request.DwellingType);
            return WriteJson(returnData);
        }


        #endregion

        #region Task, Tips and Ideas Services

        public Stream getApp_GetTasks(TasksRequest request)
        { 
            var service = new TasksAppService();
            var returnData = service.GetTasksList(request);
            List<Task> tasks = new List<Task>();
            returnData.ForEach(tk => {
                var newTask = new Task(tk);
                tasks.Add(newTask);
            });

            return WriteJson(tasks);
        }

        public Stream getApp_DoneTask(DoneTaskRequest request)
        {
            var service = new TasksAppService();
            var returnData = service.DoneTask(request);

            var dictionaryData = new Dictionary<string, string>();
            dictionaryData.Add("Result", returnData);

            return WriteJson(dictionaryData);
        }

        public Stream getApp_TurnOffTask(TurnOffTaskRequest request)
        {
            var service = new TasksAppService();
            var returnData = service.TurnOffTask(request);

            var dictionaryData = new Dictionary<string, string>();
            dictionaryData.Add("Result", returnData);

            return WriteJson(dictionaryData);
        }

        //public Stream getApp_GetIdeas(TasksRequest request)
        //{
        //    var service = new IdeaAppService();
        //    var returnData = service.GetIdeaList(request);
        //    List<Idea> ideas = new List<Idea>();
        //    returnData.ForEach(ia => {
        //        var newIdea = new Idea(ia);
        //        ideas.Add(newIdea);
        //    });
        //    return WriteJson(ideas);
        //}

        //public Stream getApp_GetTips(TasksRequest request)
        //{
        //    var service = new TipsAppService();
        //    var returnData = service.GetTipsList(request);
        //    List<Tip> tips = new List<Tip>();
        //    returnData.ForEach(tp =>
        //    {
        //        var newTip = new Tip(tp);
        //        tips.Add(newTip);
        //    });
        //    return WriteJson(tips);
        //}

        #endregion

        private static Stream WriteJson(object value)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(serializer.Serialize(value)));
            return stream;
        }

        #region old webservice functions
        public Stream getApp_Check_Promocode(string postdata)
        {
            var service = new SponsorAppService();
            var returnData = service.CheckPromoCode(new CheckPromocodeRequest
            {
                PromoCode = postdata
            });

            var dictionaryData = new Dictionary<string, string>();
            returnData.ForEach(promoCode =>
            {
                dictionaryData.Add(promoCode.promocode, promoCode.PromocodeCheck);
            });

            return WriteJson(dictionaryData);
        }

        public Stream getApp_Initial_Setup(Stream stream)
        {
            return DataAccess.getApp_Initial_Setup(stream);
        }

        public Stream getApp_Initial_Login(Stream stream)
        {
            return DataAccess.getApp_Initial_Login(stream);
        }

        public Stream getApp_Forgot_Password(Stream stream)
        {
            return DataAccess.getApp_Forgot_Password(stream);
        }

        public Stream getIdeas(Stream stream)
        {
            return DataAccess.getIdeas(stream);
        }

        public Stream getFeedBack(string feedback)
        {
            return DataAccess.getFeedBack(feedback);
        }

        public Stream getTips(Stream stream)
        {
            return DataAccess.getTips(stream);
        }

        public Stream getRoutineTasks(Stream stream)
        {
            return DataAccess.getRoutineTask(stream);
        }

        public Stream getApp_Reopen(Stream stream)
        {
            //var service = new AppRefreshAppService();
            //var returnData = service.AppReopen(request);
            //if (returnData != null)
            //{
            //    return WriteJson(new User(returnData));
            //}
            //return WriteJson(returnData);
            return DataAccess.getApp_Reopen(stream);
        }
        #endregion
    }
}

>>>>>>> .r402
